Spring AOP Brief

AOP stands for Aspect Oriented Programming, allow you insert extra logics

Ways to declare point cut

Case #1, declare point cut outside target package

1
2
3
4
5
6
7
@Pointcut("@annotation(com.xxx.SomeAnnotation)")
public void PointCutMethod() {}

@Before("PointCutMethod()")
public beforePointCutMethod(JoinPoint joinPoint) {
// do some thing
}

Case #2, declare point cut inside target package

1
2
3
4
5
6
7
8
// namespace of SomeAnnotation was removed
@Pointcut("@annotation(SomeAnnotation)")
public void PointCutMethod() {}

@Before("PointCutMethod()")
public beforePointCutMethod(JoinPoint joinPoint) {
// do some thing
}

Case #3, declare point cut by advice directly

1
2
3
4
@Around("@annotation(com.xxx.SomeAnnotation)")
public beforePointCutMethod(JoinPoint joinPoint) {
// do some thing
}

Advices types

@Before & @After, do something before or after the method execution

1
2
3
4
@Before("PointCutMethod()")
public beforeAdvice(JoinPoint joinPoint) {
// do some thing
}

@Around, execute method by calling prceed() of ProceedingJoinPoint. So you can do things around the execution.

1
2
3
4
5
6
@Around("PointCutMethod()")
public aroundAdvice(ProceedingJoinPoint joinPoint) {
// do some thing
joinPoint.proceed();
// do some thing eles
}

@AfterReturning, can get the retrun value after the method execution

1
2
3
@AfterReturning(PointCut = "PointCutMethod()", returning = "retVal")
public void afterReturningAdvice(JoinPoint jp, Object retVal){
}

@AfterThrowing, can get the exeception if the method throws

1
2
3
@AfterThrowing(PointCut = "PointCutMethod()", throwing = "error")
public void afterThrowingAdvice(JoinPoint jp, Throwable error){
}

PointCut Expression

PointCut declare where the advices should work on

Visite this very useful site about PointCut Expression